package fnsvr

import (
	"runtime/debug"
	"sync"
)

// EventType 定义事件类型
type EventType string

// EventHandler 定义事件处理函数类型
type EventHandler func(data interface{})

// EventSystem 事件系统结构体
type EventSystem struct {
	handlers map[EventType][]EventHandler
	lock     sync.RWMutex
}

// NewEventSystem 创建一个新的事件系统
func NewEventSystem() *EventSystem {
	return &EventSystem{
		handlers: make(map[EventType][]EventHandler),
	}
}

// RegisterHandler 注册事件处理函数
func (es *EventSystem) RegisterHandler(eventType EventType, handler EventHandler) {
	es.lock.Lock()
	defer es.lock.Unlock()

	es.handlers[eventType] = append(es.handlers[eventType], handler)
}

// TriggerEvent 触发事件
func (es *EventSystem) TriggerEvent(eventType EventType, data interface{}) {
	es.lock.RLock()
	defer es.lock.RUnlock()

	if handlers, ok := es.handlers[eventType]; ok {
		for _, handler := range handlers {
			// 立即执行事件处理函数
			es.callHandler(eventType, handler, data)
		}
	}
}

func (es *EventSystem) callHandler(eventType EventType, handler EventHandler, data interface{}) {

	defer func() {
		if r := recover(); r != nil {

			Log().Error(
				"EventSystem::callHandler",
				"eventType", eventType,
				"data", data,
				"Stack", debug.Stack(),
			)
		}
	}()

	handler(data)
}
